package controller

import (
	"encoding/json"
	"ez/apps/tool/service"
	"ez/apps/wms/auto/controller"
	"ez/apps/wms/conf"
	wms "ez/apps/wms/document"
	"ez/config/code"
	"ez/custom/cc"
	"fmt"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"time"
)

type InLogController struct {
	controller.InLogAutoController
}

func init() {
	c := &InLogController{}
	c.SetRouteParam("/wms", "/admin", "InLog")
	ez.CreateApi(c.AdminGet(), c.GetAction).SetRouterName("[wms]入库记录_创建")
	ez.CreateApi(c.AdminList(), c.ListAction).SetRouterName("[wms]入库记录_列表")
	ez.CreateApi(c.AdminSave(), c.SaveAction).SetRouterName("[wms]入库记录_保存")
	ez.CreateApi(c.AdminCopy(), c.CopyAction).SetRouterName("[wms]入库记录_复制")
	ez.CreateApi(c.AdminUpdate(), c.UpdateAction).SetRouterName("[wms]入库记录_更新")
	ez.CreateApi(c.AdminChoice(), c.ChoiceAction).SetRouterName("[wms]入库记录_选项")
	ez.CreateApi(c.AdminDelete(), c.DeleteAction).SetRouterName("[wms]入库记录_删除")
	ez.CreateApi(c.AdminUnDelete(), c.UnDeleteAction).SetRouterName("[wms]入库记录_恢复")
	ez.CreateApi(c.AdminDestroy(), c.DestroyAction).SetRouterName("[wms]入库记录_销毁")
	ez.CreateApi(c.AdminUpdateMany(), c.UpdateManyAction).SetRouterName("[wms]入库记录_更新_批量")
	ez.CreateApi(c.AdminDeleteMany(), c.DeleteManyAction).SetRouterName("[wms]入库记录_删除_批量")
	ez.CreateApi(c.AdminDestroyMany(), c.DestroyManyAction).SetRouterName("[wms]入库记录_销毁_批量")
	ez.CreateApi(c.AdminApi("/InLog/in_many"), c.InManyAction).SetRouterName("[wms]入库记录_批量入库")
	ez.CreateApi(c.AdminApi("/InLog/in_cancel"), c.InCancelAction).SetRouterName("[wms]入库记录_入库红冲")
}

// func (c InLogController) AccessControl(session *ez.Session) { /* 在这里面重构 */ }
// func (c InLogController) GetAction(session *ez.Session) { /* 在这里面重构 */ }
// func (c InLogController) ListAction(session *ez.Session) { /* 在这里面重构 */ }
type InManyQuery struct {
	List []struct {
		ItemId    int64   `json:"itemId"`
		Num       float64 `json:"num"`
		Pos       string  `json:"pos"`
		BatchCode string  `json:"batchCode"`
		HeapCode  string  `json:"heapCode"`
		//DepartmentId string  `json:"departmentId"`
		Brand string  `json:"brand"`
		Note  string  `json:"note"`
		Cost  float64 `json:"cost"`
	} `json:"list"`
	Model wms.InLog `json:"model"`
}

func (c *InLogController) InManyAction(session *ez.Session) {
	this := cc.New(session)
	query := new(InManyQuery)
	e := this.FillJson(query)
	if this.CheckError(e) {
		return
	}
	//逐条拆解到出库记录
	if len(query.List) == 0 {
		this.ReturnError(code.Error, "未选择任何记录", "")
		return
	}
	if query.Model.TypeId == 0 {
		this.ReturnError(code.Error, "请选择入库类型", "")
		return
	}
	//本次循环只是检查数据什么业务也不做
	itemCrud := wms.NewItemSkuCrud()
	toSaveIn := make([]*wms.InLog, 0)
	if query.Model.Sn == "" {
		//如果创建批次号
		query.Model.Sn = service.CreateSnByString(ez.ConfigService.AppId, "StoreInSn:[YY][MM][DD][DMAX[3]]", 1)[len("StoreInSn:"):]
	}
	for _, row := range query.List {
		find, e := itemCrud.FindOneBy(ss.M{"id": row.ItemId}, nil)
		if this.CheckError(e) {
			return
		}
		if find.Id == 0 {
			this.ReturnError(code.Error, fmt.Sprintf("数据丢失，ID:%d", row.ItemId), "")
			return
		}
		if row.Num == 0 {
			this.ReturnError(code.Error, fmt.Sprintf("%s数量为0", find.Text), "")
			return
		}
		log := new(wms.InLog)
		log.ItemId = row.ItemId

		log.Pos = row.Pos
		log.BatchCode = row.BatchCode
		log.HeapCode = row.HeapCode
		log.Brand = row.Brand
		log.Note = row.Note

		log.NumInReal = row.Num
		log.NumIn = row.Num
		log.NumLeft = row.Num

		log.BatchPrice = row.Cost / row.Num
		log.Cost = row.Cost
		log.CostReal = row.Cost

		log.DepartmentId = query.Model.DepartmentId
		log.TypeId = query.Model.TypeId
		log.Sn = query.Model.Sn
		log.Supplier = query.Model.Supplier
		toSaveIn = append(toSaveIn, log)
	}
	for _, log := range toSaveIn {
		log.SetEvent(true)
		_ = log.Save()
	}

	this.ReturnSuccess("OK", "")
}

type inCancelQuery struct {
	InLogId int    `json:"inLogId"`
	Note    string `json:"note"`
	Applier string `json:"applier"` //经办人
	Pos     string `json:"pos"`
}

func (c *InLogController) InCancelAction(session *ez.Session) {
	this := cc.New(session)
	query := new(inCancelQuery)
	e := this.FillJson(&query)
	if this.CheckError(e) {
		return
	}
	//校验数据合理性 、、todo 这里没有强行校验 是否有出库数量，为了增加易用性
	crud := wms.NewInLogCrud()
	find, e := crud.FindOneBy(ss.M{"id": query.InLogId}, nil)
	if this.CheckError(e) {
		return
	}
	if find.Id == 0 {
		this.ReturnError(code.Error, "请选择有效入库数据", "InLogId")
		return
	}
	//创建红冲数据
	cancelLog := new(wms.InLog)
	jsonFind, e := json.Marshal(find)
	if this.Try(e) {
		return
	}
	if this.Try(json.Unmarshal(jsonFind, &cancelLog)) {
		return
	}
	cancelLog.Id = 0
	cancelLog.CreateAt = time.Now()
	cancelLog.Note = query.Note
	cancelLog.TypeId = conf.InCancelTpeId
	cancelLog.DepartmentId = find.DepartmentId
	cancelLog.IsCanceled = true
	cancelLog.NumIn = cancelLog.NumLeft * -1
	cancelLog.NumInReal = cancelLog.NumLeft * -1
	cancelLog.NumLeft = 0
	cancelLog.NumOut = 0
	//退库的内容直接红冲会出问题
	if cancelLog.Cost != 0 {
		cancelLog.Cost *= -1
	} else {
		cancelLog.Cost = cancelLog.BatchPrice * cancelLog.NumLeft * -1
	}
	cancelLog.CostReal *= -1
	cancelLog.LinkTo = find.Link
	cancelLog.Link = ""

	//同时清空原始记录的NumLeft
	find.IsCanceled = true
	find.NumLeft = 0

	find.Save()
	cancelLog.Save()

	this.ReturnSuccess("OK", "")

}
